package org.chen.ctrip.service.translate.service;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.scene.ollama.OllamaRequest;
import org.chen.common.scene.ollama.OllamaResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ContentTranslationService {

    private final RestTemplate ollamaRestTemplate;

    @Autowired
    private BaiduTranslationService baiduTranslationService;

    @Value("${ollama.embedding.base-url:http://8.219.169.114:11434}")
    private String OLLAMA_BASE_URL;

    @Value("${ollama.embedding.model2:mistral-nemo:12b}")
    private String ollamaModel;

    private static final String DAY_SUMMARY_PROMPT = """
            你是一名专业的旅游内容编辑。请将以下旅游行程内容进行精简总结，转换为简洁清晰的Markdown格式。
            要求：
            1. 保持行程的时间顺序和主要信息
            2. 删除重复和冗余的内容
            3. 保留关键的行程标题、景点名称、景点介绍、时间、费用、交通等信息
            4. 使用简洁的Markdown格式，适合翻译成其他语言
            5. 删除HTML样式相关的内容和过于详细的说明
            6. 每个时间点用二级标题，景点用加粗显示
            7. 费用信息用列表形式展示
            8. 总结后的内容应该比原文简洁30-50%%
            9. 只输出总结后的Markdown内容，不要其他说明
            
            原始内容：
            %s
            """;

    public ContentTranslationService(RestTemplate ollamaRestTemplate) {
        this.ollamaRestTemplate = ollamaRestTemplate;
    }

    /**
     * 使用Ollama总结多天行程内容
     */
    public List<String> summarizeDayContents(List<String> dayContents) {
        List<String> summarizedDays = new ArrayList<>();

        for (int i = 0; i < dayContents.size(); i++) {
            try {
                String dayContent = dayContents.get(i);
                String summarized = summarizeSingleDayWithOllama(dayContent, i + 1);
                summarizedDays.add(summarized);

                // 添加小延时避免API调用过于频繁
                Thread.sleep(1000);

            } catch (Exception e) {
                log.error("总结第{}天内容失败: {}", i + 1, e.getMessage());
                // 如果总结失败，使用原内容（但会很长）
                log.warn("第{}天总结失败，使用原始内容", i + 1);
                summarizedDays.add(dayContents.get(i));
            }
        }

        return summarizedDays;
    }

    /**
     * 使用百度翻译API翻译多天内容
     */
    public List<String> translateDayContentsByBaidu(List<String> dayContents, String targetLanguage) {
        List<String> translatedDays = new ArrayList<>();
        String baiduLangCode = convertToBaiduLanguageCode(targetLanguage);

        for (int i = 0; i < dayContents.size(); i++) {
            try {
                String dayContent = dayContents.get(i);

                // 检查内容长度，百度翻译有长度限制
                if (dayContent.length() > 6000) {
                    log.warn("第{}天内容过长({})，进行分段翻译", i + 1, dayContent.length());
                    String translated = translateLongContentBySegments(dayContent, baiduLangCode, i + 1);
                    translatedDays.add(translated);
                } else {
                    String translated = baiduTranslationService.translate(dayContent, "zh", baiduLangCode);
                    translatedDays.add(translated);
                }

                log.info("第{}天内容翻译完成，原长度: {}, 译后长度: {}",
                        i + 1, dayContent.length(), translatedDays.get(i).length());

                // 添加延时避免API限制
                Thread.sleep(1500);

            } catch (Exception e) {
                log.error("翻译第{}天内容失败: {}", i + 1, e.getMessage());
                // 如果翻译失败，保留原文
                log.warn("第{}天翻译失败，保留原文", i + 1);
                translatedDays.add(dayContents.get(i));
            }
        }

        return translatedDays;
    }

    /**
     * 分段翻译长内容
     */
    private String translateLongContentBySegments(String content, String targetLang, int dayNumber) {
        try {
            // 按段落分割内容
            String[] paragraphs = content.split("\n\n");
            List<String> translatedParagraphs = new ArrayList<>();

            StringBuilder currentSegment = new StringBuilder();

            for (String paragraph : paragraphs) {
                // 如果当前段落加上新段落超过限制，先翻译当前段落
                if (currentSegment.length() + paragraph.length() > 5000) {
                    if (!currentSegment.isEmpty()) {
                        String translated = baiduTranslationService.translate(
                                currentSegment.toString(), "zh", targetLang);
                        translatedParagraphs.add(translated);
                        currentSegment = new StringBuilder();

                        // 短暂延时
                        Thread.sleep(1000);
                    }
                }

                if (!currentSegment.isEmpty()) {
                    currentSegment.append("\n\n");
                }
                currentSegment.append(paragraph);
            }

            // 翻译最后一段
            if (!currentSegment.isEmpty()) {
                String translated = baiduTranslationService.translate(
                        currentSegment.toString(), "zh", targetLang);
                translatedParagraphs.add(translated);
            }

            return String.join("\n\n", translatedParagraphs);

        } catch (Exception e) {
            log.error("分段翻译失败，第{}天", dayNumber, e);
            throw new RuntimeException("分段翻译失败: " + e.getMessage());
        }
    }

    /**
     * 使用Ollama总结单天内容
     */
    private String summarizeSingleDayWithOllama(String dayContent, int dayNumber) {
        try {
            String prompt = String.format(DAY_SUMMARY_PROMPT, dayContent);

            OllamaRequest request = new OllamaRequest();
            request.setModel(ollamaModel);
            request.setPrompt(prompt);
            request.setStream(false);

            OllamaRequest.Options options = new OllamaRequest.Options();
            options.setTemperature(0.2); // 低温度确保一致性
            options.setNum_predict(1024); // 限制输出长度
            request.setOptions(options);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<OllamaRequest> httpEntity = new HttpEntity<>(request, headers);

            log.info("调用Ollama API总结第{}天内容", dayNumber);

            ResponseEntity<OllamaResponse> responseEntity = ollamaRestTemplate.postForEntity(
                    OLLAMA_BASE_URL + "/api/generate",
                    httpEntity,
                    OllamaResponse.class
            );

            OllamaResponse ollamaResponse = responseEntity.getBody();

            if (ollamaResponse != null && ollamaResponse.getResponse() != null) {
                String summarizedContent = ollamaResponse.getResponse().trim();
                log.info("第{}天内容总结完成，原长度: {}, 总结后长度: {}",
                        dayNumber, dayContent.length(), summarizedContent.length());
                return summarizedContent;
            } else {
                throw new RuntimeException("未收到有效的Ollama响应");
            }

        } catch (Exception e) {
            log.error("Ollama总结第{}天内容失败: {}", dayNumber, e.getMessage());
            throw new RuntimeException("内容总结失败: " + e.getMessage());
        }
    }

    /**
     * 合并多天内容
     */
    public String mergeDayContents(List<String> dayContents) {
        StringBuilder merged = new StringBuilder();

        for (int i = 0; i < dayContents.size(); i++) {
            if (i > 0) {
                merged.append("\n\n---\n\n");
            }
            merged.append(dayContents.get(i));
        }

        return merged.toString();
    }

    /**
     * 转换语言代码为百度翻译支持的格式
     */
    private String convertToBaiduLanguageCode(String languageCode) {
        return switch (languageCode.toLowerCase()) {
            case "en", "en-us" -> "en";
            case "ja", "ja-jp" -> "jp";
            case "ko", "ko-kr" -> "kor";
            case "fr", "fr-fr" -> "fra";
            case "de", "de-de" -> "de";
            case "es", "es-es" -> "spa";
            case "ru", "ru-ru" -> "ru";
            case "th", "th-th" -> "th";
            default -> "en"; // 默认英语
        };
    }

    /**
     * 获取处理统计信息
     */
    public ProcessingStats getProcessingStats(List<String> originalContents, List<String> finalContents) {
        ProcessingStats stats = new ProcessingStats();

        int originalTotalLength = originalContents.stream().mapToInt(String::length).sum();
        int finalTotalLength = finalContents.stream().mapToInt(String::length).sum();

        stats.setDayCount(originalContents.size());
        stats.setOriginalTotalLength(originalTotalLength);
        stats.setFinalTotalLength(finalTotalLength);

        return stats;
    }

    /**
     * 处理统计信息类
     */
    @Data
    public static class ProcessingStats {
        private int dayCount;
        private int originalTotalLength;
        private int finalTotalLength;
        @Override
        public String toString() {
            return String.format("统计信息: %d天, 原始%d字符, 处理后%d字符",
                    dayCount, originalTotalLength, finalTotalLength);
        }
    }
}